#include "datapage.h"
#include "ui_datapage.h"
#include "util/messagebox.h"
#include <QJsonArray>
#include <QJsonObject>
#include <QDebug>
#include <QFont>
#include <QScrollArea>

// QtCharts namespace is used via QT_CHARTS_USE_NAMESPACE in .h

namespace WordMemory
{
    DataPage::DataPage(QWidget *parent)
        : QWidget(parent)
        , ui(new Ui::DataPage)
        , serverhelper(new ServerHelper(this))
        , m_chart(nullptr)
    {
        ui->setupUi(this);
        setupConnections();

        m_chart = new QChart();
        m_chart->setAnimationOptions(QChart::SeriesAnimations);

        QFont chartFont("Microsoft YaHei", 9);
        m_chart->setFont(chartFont);

        m_chart->legend()->setVisible(true);
        m_chart->legend()->setAlignment(Qt::AlignBottom);
        m_chart->legend()->setFont(QFont("Microsoft YaHei", 8));

        ui->dailyStatsChartView->setChart(m_chart);
        ui->dailyStatsChartView->setRenderHint(QPainter::Antialiasing);

        QFont pageTitleFont("Microsoft YaHei", 50, QFont::Bold);
        ui->titleLabel->setFont(pageTitleFont);

        ui->chartScrollArea->setWidgetResizable(true);
        ui->dailyStatsChartView->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

        refreshPageData();
    }

    DataPage::~DataPage()
    {
        delete ui;
    }

    void DataPage::refreshPageData() {
        fetchDailyStats();
    }

    void DataPage::setupConnections()
    {
        connect(serverhelper, &ServerHelper::getDailyLearningSummaryFinished, this,
                [this](bool success, const QJsonArray &summary, const QString &error) {
                    if (success) {
                        displayDailyStatsChart(summary);
                    } else {
                        MessageBox::warning(this, "获取每日学习数据失败: " + error);
                        m_chart->removeAllSeries();
                        QList<QAbstractAxis*> currentXAxes = m_chart->axes(Qt::Horizontal);
                        for(QAbstractAxis* axis : currentXAxes) { m_chart->removeAxis(axis); delete axis; }
                        QList<QAbstractAxis*> currentYAxes = m_chart->axes(Qt::Vertical);
                        for(QAbstractAxis* axis : currentYAxes) { m_chart->removeAxis(axis); delete axis; }
                        ui->dailyStatsChartView->setMinimumWidth(0);
                    }
                });
    }

    void DataPage::fetchDailyStats()
    {
        if (!UserManager::instance().isLoggedIn()) {
            m_chart->removeAllSeries();
            QList<QAbstractAxis*> currentXAxes = m_chart->axes(Qt::Horizontal);
            for(QAbstractAxis* axis : currentXAxes) { m_chart->removeAxis(axis); delete axis; }
            QList<QAbstractAxis*> currentYAxes = m_chart->axes(Qt::Vertical);
            for(QAbstractAxis* axis : currentYAxes) { m_chart->removeAxis(axis); delete axis; }
            ui->dailyStatsChartView->setMinimumWidth(0);
            return;
        }
        int userId = UserManager::instance().getUserId();
        serverhelper->getDailyLearningSummary(userId, 30);
    }

    void DataPage::displayDailyStatsChart(const QJsonArray &dailyData)
    {
        m_chart->removeAllSeries();
        QList<QAbstractAxis*> currentXAxes = m_chart->axes(Qt::Horizontal);
        for(QAbstractAxis* axis : currentXAxes) { m_chart->removeAxis(axis); delete axis; }
        QList<QAbstractAxis*> currentYAxes = m_chart->axes(Qt::Vertical);
        for(QAbstractAxis* axis : currentYAxes) { m_chart->removeAxis(axis); delete axis; }

        if (dailyData.isEmpty()) {
            ui->dailyStatsChartView->setMinimumWidth(0);
            MessageBox::show(this, Log::Error, "近30天无学习记录");
            return;
        }

        QBarSet *forgotSet = new QBarSet("忘记");
        QBarSet *vagueSet = new QBarSet("模糊");
        QBarSet *knownSet = new QBarSet("认识");

        forgotSet->setColor(QColor(255, 77, 79));
        vagueSet->setColor(QColor(250, 173, 20));
        knownSet->setColor(QColor(82, 196, 26));

        QStringList categories;
        qreal maxObservedYValue = 0;

        for (const QJsonValue &val : dailyData) {
            QJsonObject dayStat = val.toObject();
            QString dateStr = dayStat["date"].toString();
            QDate qDate = QDate::fromString(dateStr, "yyyy-MM-dd");
            categories << qDate.toString("MM-dd");

            int forgot = dayStat["forgot"].toInt();
            int vague = dayStat["vague"].toInt();
            int known = dayStat["known"].toInt();

            *forgotSet << forgot;
            *vagueSet << vague;
            *knownSet << known;

            if (forgot + vague + known > maxObservedYValue) {
                maxObservedYValue = forgot + vague + known;
            }
        }

        QStackedBarSeries *series = new QStackedBarSeries(m_chart);
        series->append(forgotSet);
        series->append(vagueSet);
        series->append(knownSet);

        series->setLabelsVisible(true);
        series->setLabelsPosition(QAbstractBarSeries::LabelsInsideEnd);
        series->setLabelsFormat("@value");

        QFont barLabelsFont("Microsoft YaHei", 7);
        //series->setLabelsFont(barLabelsFont);

        series->setBarWidth(0.6);

        m_chart->addSeries(series);

        QBarCategoryAxis *axisX = new QBarCategoryAxis(m_chart);
        axisX->append(categories);
        axisX->setLabelsAngle(-60);
        axisX->setLabelsFont(QFont("Microsoft YaHei", 8));
        m_chart->addAxis(axisX, Qt::AlignBottom);
        series->attachAxis(axisX);

        QValueAxis *axisY = new QValueAxis(m_chart);
        axisY->setLabelFormat("%d");
        axisY->setLabelsFont(QFont("Microsoft YaHei", 8));


        qreal yAxisMax = 10.0;
        if (maxObservedYValue > yAxisMax) {
            yAxisMax = maxObservedYValue + maxObservedYValue * 0.1 + 1;
        }

        axisY->setRange(0, yAxisMax);


        m_chart->addAxis(axisY, Qt::AlignLeft);
        series->attachAxis(axisY);

        int categoryCount = categories.count();
        int minCategoryWidth = 70; // 稍微增加每个类别的宽度，以获得更大的间隔
        int estimatedChartWidth = categoryCount * minCategoryWidth;
        estimatedChartWidth += 150; // Padding

        ui->dailyStatsChartView->setMinimumWidth(estimatedChartWidth);
        if (ui->chartScrollArea->widget()) {
             ui->chartScrollArea->widget()->setMinimumWidth(estimatedChartWidth);
        }

        m_chart->setMargins(QMargins(10, 10, 10, 30)); // 增加底部边距给X轴标签
    }
}
